<template>
  <div class="search-container">
    <form action="/">
      <van-search
        v-model="value"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="$router.back()"
        background="#3296fa"
        @focus="isEnter = false"
      />
    </form>
    <search-history
      @clearHistory="clearFn"
      :searchHistorys="searchHistorys"
      @search="onSearch"
      v-if="value.trim() === ''"
    ></search-history>
    <search-result
      :value="value"
      v-else-if="isEnter && value.trim() !== ''"
    ></search-result>
    <search-suggestion
      :value="value"
      v-else
      @onSearch="onSearch"
    ></search-suggestion>
  </div>
</template>

<script>
import searchHistory from '@/views/search/components/searchHistory'
import searchResult from '@/views/search/components/searchResult'
import searchSuggestion from '@/views/search/components/searchSuggestion'
import { setItem, getItem } from '@/utils/storage'
export default {
  name: 'SearchIndex',
  components: {
    searchHistory,
    searchResult,
    searchSuggestion
  },
  data () {
    return {
      value: '',
      isEnter: false,
      searchHistorys: getItem('SEARCH-HISTORYS') || []
    }
  },
  methods: {
    onSearch (val) {
      this.value = val
      this.isEnter = true
      console.log(val)

      // 保存搜索的记录到本地
      const index = this.searchHistorys.indexOf(val)
      if (index !== -1) {
        this.searchHistorys.splice(index, 1)
      }
      this.searchHistorys.unshift(val)
      // 限制历史记录为10条
      if (this.searchHistorys.length > 10) {
        this.searchHistorys.pop()
      }
    },
    clearFn () {
      this.searchHistorys = []
    }
  },
  watch: {
    searchHistorys (val) {
      setItem('SEARCH-HISTORYS', val)
    }
  }
}
</script>

<style scoped lang="less">
.search-container {
  .van-search__action {
    color: #fff;
    &:active {
      background-color: unset;
    }
  }
}
</style>
